package com.dgut.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dgut.dto.Result;
import com.dgut.mapper.AccountMapper;
import com.dgut.pojo.Account;
import com.dgut.pojo.UserInfo;
import com.dgut.service.AccountService;
import com.dgut.utils.JwtTokenUtil;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户登录省份验证：外调新版的认证系统·
 * 
 * @author xiaoyan
 * @version 创建时间：2017年8月7上午10:15:40
 *    
 */

@CrossOrigin(origins = "*",maxAge = 3600)
@RestController
public class LoginController {

	// 设置应用系统的AppID，每个应用都不同，你要先去申请注册
	private static String appId = "javaee";

	// 设置应用系统的appSecret，每个应用都不同，你要先去申请注册
	private static String appSecret = "b3b52e43ccfd";

	// '中央认证登录页
	private static String CAS_Server = "http://cas.zemcho.com/";    //要换你自己的
	// -----------
	private static String casLoginUrl = "https://cas.dgut.edu.cn?appid=javaee&state=STATE";   ////要换你自己的

	// '中央认证兑票页
	private static String httpService = "https://cas.dgut.edu.cn/ssoapi/v2/checkToken";    //不用换

	// 获取用户信息
	private static String userInfoService = "https://cas.dgut.edu.cn/oauth/getUserInfo";   //不用换
	@Resource
	private AccountMapper accountMapper;
	@Resource
	private AccountService accountService;
	@Resource
	private JwtTokenUtil jwtTokenUtil;

	/*
	 * 
	 * 1 第一步，用户发起登录，获取token
	 * 用户发起用登录，APP端携带appid请求服务端，服务端验证app合法性，app合法性通过后用户输入账号密码提交，中央认证验证合法性后
	 *
	 * 2第二步，通过token获取access_token和openid
	 * -APP端获取到token，利用token、appid和appsecret去获取access_token和openid
	 * 
	 * 3第三步，通过access_token和openid获取个人信息
	 */

	@GetMapping("/loginWithToken")
	public Result loginWithToken(@RequestParam("token") String token, HttpServletRequest request){
		Result result = new Result();
		String ip = "120.79.14.226";
		System.out.println("token===" + token);
		String userIp = request.getLocalAddr();
		System.out.println("userIp===" + userIp);
		// 开始访问接口，验证token值
		try {
			Map<String, String> userInfo = postToken(token, userIp);  //这就是中央认证后
			if(userInfo.isEmpty()){  //得不到信息
				result.setCode(0);
				result.setMsg("用户名或者密码不存在");
				return result;
			}
			//注册账号
			if(accountMapper.getAccountByUsername(userInfo.get("username"))==null){
				Account account = new Account();
				account.setUsername(userInfo.get("username"));
				UserInfo userInfo1 = new UserInfo();
				userInfo1.setName(userInfo.get("name"));
				if(userInfo.get("group").equals("Student")){
					userInfo1.setIdentityCategory("学生用户");
				}
				else userInfo1.setIdentityCategory("教职员工");
				userInfo1.setDepartment(userInfo.get("facultyTitle"));
				try {
					accountService.addAccount(account,userInfo1);
				} catch (Exception e) {
					result.setCode(0);
					result.setMsg("登录失败");
					return result;
				}
			}
			//生成一个token
			Account account1 = accountMapper.getAccountByUsername(userInfo.get("username"));
			final String token1 = jwtTokenUtil.generateToken(userInfo.get("username"));
			HashMap<String, Object> map = new HashMap<>();
			List<GrantedAuthority> authLists = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_"+account1.getRole());
			map.put("token",token1);
			map.put("authorities",authLists);
			result.setCode(200);
			result.setMsg("登录成功");
			result.setData(map);
		} catch (IOException e) {
			result.setCode(0);
			result.setMsg("登录失败");
			return result;
		}
		return result;
	}


//	@ResponseBody
//	@RequestMapping(value = "/login")
//	public void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
//		// 1从中央验证系统获取token
//		String token = request.getParameter("token");
//		String username = request.getParameter("username");
//		String password = request.getParameter("password");
//		System.out.println("token==============================" + token);
//		// 没有Token，把用户重定向到中央认证登陆页
//		if (token == null || "".equals(token)) {
//			System.out.println("token为空格");
//			// 跳到中央登录登录验证系统，这个异常判断
//			response.sendRedirect(casLoginUrl);
//		} else {
//			// 有票，开始兑票------第二步，通过token获取access_token和openid
//			String ip = "172.27.15.28";
//			System.out.println("token===" + token);
//			String userIp = request.getLocalAddr();
//			System.out.println("userIp===" + userIp);
//			// 开始访问接口，验证token值
//			Map<String, String> userInfo = postToken(token, userIp);  //这就是中央认证后你拿到的用户信息了
//		}
//	}

	/*
	 * 2第二步，通过token获取access_token和openid
	 * -APP端获取到token，利用token、appid和appsecret去获取access_token和openid
	 * 
	 * 3第三步，通过access_token和openid获取个人信息
	 */
	private Map<String, String> postToken(String token, String useip) throws ParseException, IOException {
		String myToken = token;
		String url = httpService;
		Map<String, String> userInfo  =   new HashMap<String,String>();
		//HttpClient httpClient = new DefaultHttpClient();
		HttpClient httpClient = GetHttpClient.getHttpClient();
		String json = jsonMethod(token, useip, appId, appSecret);
		HttpPost post = new HttpPost(url);
		StringEntity postingString = new StringEntity(json);// json传递
		post.setEntity(postingString);
		post.setHeader("Content-type", "application/json");
		HttpResponse response = httpClient.execute(post);
		String content = EntityUtils.toString(response.getEntity());
		if(content != null || "".equals(content)){
			Map<String, String> map = JSON.parseObject(content, Map.class);
			String openid = map.get("openid");
			String accessToken = map.get("access_token");
			if(openid != null || "".equals(openid)){
				userInfo = getUserInfo(accessToken,openid);
				System.out.println("userInfo=="+userInfo);
			}
		}
		post.releaseConnection();
		System.out.println("postToken=="+content);
		return userInfo;

	}

	/*
	 * 第三步：通过access_token和openid获取个人信息
	 */
	private Map<String, String> getUserInfo(String aaccessToken, String openid) throws ParseException, IOException {
		Map<String, String> infoMap = new HashMap<String,String>();
		//HttpClient httpClient = new DefaultHttpClient();
		HttpClient httpClient = GetHttpClient.getHttpClient();
		HttpPost post = new HttpPost(userInfoService);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("access_token", aaccessToken);
		jsonObject.put("openid", openid);
		String jsonstr = JSONObject.toJSONString(jsonObject);
		StringEntity postingString = new StringEntity(jsonstr);// jsonstr传递
		post.setEntity(postingString);
		post.setHeader("Content-type", "application/json");
		HttpResponse response = httpClient.execute(post);
		String content = EntityUtils.toString(response.getEntity());
		System.out.println("getUserInfocontent=="+content);
		if(content != null || "".equals(content)){
			////获取用户信息
			Map<String, String> map = JSON.parseObject(content, Map.class);
			String username = map.get("username");  //学号
			String name = map.get("name");    //姓名
			String group = map.get("group");  //身份类别
			String facultyTitle = map.get("faculty_title");  //学院
//			BeanUtils.copyProperties(source, target);
			if(username != null || "".equals(username)){
				infoMap.put("username",username);
				infoMap.put("name",name);
				infoMap.put("group",group);
				infoMap.put("facultyTitle",facultyTitle);
			}
		}
		post.releaseConnection();
		return infoMap;
	}

	/*
	 * 参数名 是否必须 类型 说明
	 *  token 是 string 
	 *  上一步获取的token 
	 *  appid 是 string appid appsecret
	 * 是 string app密钥 userip 是 string ip地址
	 */
	public static String jsonMethod(String token, String userip, String appid, String appsecret) {
		System.out.println("userip==" + userip);
		String localIp = "";
		// 当在服务器上本地测试时，用户访问ip会变成10.0.2.2，而中央认证将获取到本地服务器ip，故需要手动替换
		if ("10.0.2.2".equals(userip)) {
			localIp = "120.79.14.226";
		} else {
			localIp = userip;
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("token", token);
		jsonObject.put("appid", appid);
		jsonObject.put("appsecret", appsecret);
		jsonObject.put("userip", localIp);
		String jsonstr = JSONObject.toJSONString(jsonObject);
		System.out.println("jsonMethod的jsonstr+++++====" + jsonstr);
		return jsonstr;
	}

}
